#!/opt/ActivePerl-5.14/bin/perl

use DBI;
use Carp;
use strict;
use File::Copy;
use Getopt::Long;
use File::Basename;
use XML::Simple qw(:strict);
use Mail::Sender::Easy qw(email);

my (
    $xml,  @missing, @files,  @temp, $file, %fail,
    $temp, $del,     $config, $msg,  $sbj
);

my $options = GetOptions( 'config=s' => \$config );

if ( -e $config ) {
    ( my $name, my $path, my $suffix ) = fileparse( $config, qr/\.[^.]*/ );
    if ( lc($suffix) eq '.xml' ) {
        $xml = XMLin( $config, ForceArray => 0, KeyAttr => [] );
        open LOG, ">>$xml->{logfile}" or croak;
        print {*LOG} "Job : $xml->{job} \nStart Time: " . localtime() . "\n\n"
          or croak;
        print {*LOG}
"------------------------------------------------------------------------------------------\n"
          or croak;
        print {*LOG} "found $config file.\n" or croak;
    }
    else {
        print "The file you specified is invalid."
          . "File must end with a .xml extension.\n"
          or croak;
        close LOG or croak;
        UPDATE(0);
        exit;
    }
}

else {
    print "Check the path to your file.\n"
      . "I was not able to find.\n $config\n"
      or croak;
    close LOG or croak;
    UPDATE(0);
    exit;
}

UPDATE(1);

if ( exists $xml->{files}->{file} ) {
    if ( ref( $xml->{files}->{file} ) eq 'ARRAY' ) {

        @temp = ( @{ $xml->{files}->{file} } );

        foreach $temp (@temp) {
            push @files, "$xml->{sorce}/$temp";
        }
    }
    elsif ( ref( $xml->{files}->{file} ) eq "" ) {
        push @files, "$xml->{sorce}/$xml->{files}->{file}";
    }
    else {
        print {*LOG} "Please check your XML file. \n" or croak;
        print {*LOG} "I was not able to find a proper listing of files to copy.\n" or croak;
        $msg = "Please check the XML file. There appears to be something wrong with it.\n";
        $msg = $msg . "From what I can tell there is a problem in the <files><file></file></files> section\n";
        $msg = $msg . "of the file. Please correct it and try again.\n\n";
        $msg = $msg . "Thank you,\n" . "Automize Server\n";
        $sbj = "Error - Job $xml->{job} failed. Files not found.";
        EMAIL( $msg, $sbj );
        UPDATE(0);
        close LOG or croak;
        exit;
    }
}
elsif ( exists $xml->{files}->{regex} ) {
    @files = glob "$xml->{sorce}/$xml->{files}->{regex}";
}
else {
    print {*LOG} 'No <files><file></file></files> or <files><regex></regex></files> section defined in XML file.' or croak;
    $msg = "The following XML file is not formated correctly. Please revise.\n";
    $msg = $msg . $config . "\n\n";
    $msg = $msg . 'Thank you,' . "Automize Server\n";
    $sbj = "Error - Job $xml->{job} failed please check the XML file and run again.";
    EMAIL( $msg, $sbj );
    UPDATE(0);
    close LOG or croak;
    exit;
}

if ( exists $xml->{name} ) {
    print {*LOG} "Copy Started:\n" or croak;
    print {*LOG} "-------------------------------------------------------------------------------------\n" or croak;
    foreach $file (@files) {
        if ( -e $file ) {

            if ( -d $file ) { next; }
            my (
                $dev,   $ino,     $mode, $nlink, $uid,
                $gid,   $rdev,    $size, $atime, $mtime,
                $ctime, $blksize, $blocks
            ) = stat $file;
            if ( $size == 0 ) {
                EMAIL("$file is zero bytes in size.\n\nThank you,\nAutomize Server", "Error: $xml->{job}");
                next;
            }

            unless ( copy( $file, "$xml->{destination}/$xml->{name}" ) ) {
                $fail{$file} = $!;
                print {*LOG} "$file $fail{$file}\n" or croak;
                next;
            }

			if( exists $xml->{del} ){
				if ( $xml->{del} == 1 ){
					unlink( $file );
				}
			}

            print {*LOG} "$file copied to $xml->{destination}." . "\n" or croak;
        }
        else {
            push @missing, $file;
            print {*LOG} "$file not found\n" or croak;
            next;
        }
    }
}
else {
    print {*LOG} "Copy Started:\n" or croak;
    print {*LOG} "-------------------------------------------------------------------------------------\n" or croak;
    foreach $file (@files) {
        if ( -e $file ) {

            if ( -d $file ) { next; }
            my (
                $dev,   $ino,     $mode, $nlink, $uid,
                $gid,   $rdev,    $size, $atime, $mtime,
                $ctime, $blksize, $blocks
            ) = stat $file;
            if ( $size == 0 ) {
                EMAIL( "$file is zero bytes in size.\n\nThank you,\nAutomize Server", "Error: $xml->{job}");
                next;
            }

            unless ( copy( $file, "$xml->{destination}/" ) ) {
                $fail{$file} = $!;
                print {*LOG} "$file $fail{$file}\n" or croak;
                next;
            }

			if( exists $xml->{del} ){
				if ( $xml->{del} == 1 ){
					unlink( $file );
				}
			}

            print {*LOG} "$file copied to $xml->{destination}.\n" or croak;
        }
        else {
            push @missing, $file;
            print {*LOG} "$file not found.\n" or croak;
            next;
        }
    }
}

unless ( keys(%fail) == 0 ) {
    $msg = "The following files failed to copy.\n";
    $msg = $msg . join "\n", %fail;
    $msg = $msg . "\nThank you," . 'Automize Server';
    $sbj = "Warning - Job $xml->{job} ran ran with errors.";
    UPDATE(2);
    EMAIL( $msg, $sbj );
}

unless ( scalar(@missing) == 0 ) {
    $msg = "The following files are could not be found.\n";
    $msg = $msg . join( "\n", @missing ) . "\n\n";
    $msg = $msg . "Thank you,\n" . 'Automize Server';
    $sbj = "Warning - Job $xml->{job} ran with errors.";
    UPDATE(2);
    EMAIL( $msg, $sbj );
}

sub UPDATE {
    my ($umsg) = @_;
    my $dbh = DBI->connect( 'DBI:mysql:automize:localhost',
        'automize', 'green97', { RaiseError => 1, AutoCommit => 1 } );
    my $sql =
        "UPDATE cron SET ok=$umsg, ran_at="
      . time()
      . " WHERE job=\"$xml->{job}\"";
    my $sth = $dbh->prepare($sql) or die "Failed: $sql\n";
    my $rv = $sth->execute;
    $dbh->disconnect;
}

sub EMAIL {
    my ( $emsg, $esbj ) = @_;
    email(
        {
            'from'     => 'automize@brighton.com',
            'to'       => 'autoerrors@brighton.com',
            'replyto'  => 'lcruz@brighton.com',
            'subject'  => $esbj,
            'priority' => 1,                           # 1-5 high to low
            'confirm'  => 'delivery',
            'smtp'     => '128.222.78.145',
            'port'     => 25,
            'auth'     => 'LOGIN',
            'authid'   => 'leegin\automize',
            'authpwd'  => 'ariel',
            '_text'    => $emsg,
        }
    ) or croak "email() failed: $@";
}
